package userLogic

import (
	"Server/logic"
	"Server/model"
	"Server/response"
	"Server/service"
	"crypto/md5"
	"encoding/hex"
	"github.com/gin-gonic/gin"
)

func Register(ctx *gin.Context) {
	a := ctx.Query("user_account")
	p := ctx.Query("user_password")
	var user model.User
	user.User_Account = a
	user.User_Password = p

	if service.Svc.UserProjectModel.PdOne(user) {
		response.Fail(ctx, nil, "该用户已经存在")
	} else {
		err := service.Svc.UserProjectModel.Insert(user)
		if err != nil {
			response.Fail(ctx, nil, err.Error())
		}
		user.User_id, err = service.Svc.UserProjectModel.GetId(user)
		token, err := logic.ReleaseToken(user)
		if err != nil {
			response.Fail(ctx, nil, "服务器端异常")
		}
		response.Success(ctx, gin.H{"token": token}, "注册用户成功")
	}
}

func Login(ctx *gin.Context) {
	a := ctx.Query("user_account")
	p := ctx.Query("user_password")
	var user model.User
	user.User_Account = a
	user.User_Password = p
	user1, _ := service.Svc.UserProjectModel.FindOne(user)
	user.User_id, _ = service.Svc.UserProjectModel.GetId(user)
	hasher := md5.New()
	hasher.Write([]byte(user.User_Password))
	hashedPassword := hasher.Sum(nil)
	user.User_Password = hex.EncodeToString(hashedPassword)

	if user.User_Password != user1.User_Password {
		response.Fail(ctx, nil, "账号或密码不正确")
	}
	token, err := logic.ReleaseToken(user)
	if err != nil {
		response.Fail(ctx, nil, "服务器端异常")
		return
	}
	response.Success(ctx, gin.H{"token": token}, "登陆成功")
}
